package com.example.administrator.u17.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;

import com.example.administrator.u17.R;
import com.example.administrator.u17.activity.ZhangJieActivity;
import com.example.administrator.u17.adapter.YuePiaoBaseAdapter;
import com.example.administrator.u17.config.NetConfig;
import com.example.administrator.u17.db.MyJson;
import com.example.administrator.u17.modle.Paihang;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by Administrator on 2016/11/14.
 */

public class YuepiaoFragment extends Fragment implements AdapterView.OnItemClickListener {

    private PullToRefreshListView prl;
    private List<Paihang.Data.ReturnData.Comics> list;
    private BaseAdapter mAdapter;
    private int indexPage;
    private DbManager manager;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_yuepiao, null);
        initView(view);
        initData();
        setData();
        setlistener();
        return view;
    }

    private void setlistener() {
        prl.setOnItemClickListener(this);

    }

    private void setData() {
        prl.setMode(PullToRefreshBase.Mode.BOTH);
        prl.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                //设置下拉刷新回到第一页
                indexPage = 1;
                loadData(indexPage);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                //上拉加载数据
                loadData(indexPage);
            }
        });
        prl.setAdapter(mAdapter);

    }

    private void initData() {
        list = new ArrayList<>();
        mAdapter = new YuePiaoBaseAdapter(getActivity(), list, 1);
        manager = x.getDb(new DbManager.DaoConfig());
        indexPage = 1;
        loadData(indexPage);
    }

    private void initView(View view) {
        prl = (PullToRefreshListView) view.findViewById(R.id.plv_fragment_yuepiao);

    }

    private void loadData(int page) {
        final RequestParams p = new RequestParams(NetConfig.YUEIAO_PATH + page);
        x.http().get(p, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                indexPage++;
                MyJson myjson = new MyJson();
                myjson.json = result;
                myjson.path = Environment.
                        getExternalStorageDirectory().getAbsolutePath()
                        + File.separator + "yuepiao.txt";
                try {
                    manager.delete(MyJson.class);
                    manager.save(myjson);
                } catch (DbException e) {
                    e.printStackTrace();
                }
                Paihang paihang = new Gson().fromJson(result, Paihang.class);
                for (Paihang.Data.ReturnData.Comics c : paihang.data.returnData.comics) {
                    list.add(c);
                }
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                String path = Environment.getExternalStorageDirectory().getAbsolutePath()
                        + File.separator + "yuepiao.txt";
                try {
                    List<MyJson> myjson = manager.selector(MyJson.class).where("path", "=", path).findAll();
                    Paihang paihang = new Gson().fromJson(myjson.get(0).json, Paihang.class);
                    for (Paihang.Data.ReturnData.Comics c : paihang.data.returnData.comics) {
                        list.add(c);
                    }
                    mAdapter.notifyDataSetChanged();
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                prl.onRefreshComplete();
            }
        });

    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Intent intent = new Intent(getActivity(), ZhangJieActivity.class);
        intent.putExtra("id", list.get(i - 1).comicId);
        intent.putExtra("count",list.get(i-1).conTag);
        startActivity(intent);
    }
}
